<template>
  <div class="table_container">
    <div class="table_top_btn">
      <div class="left_btn">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="openAddOrEdit(['return', 'add'], {})"
          >{{ t("button.add") }}</el-button
        >
      </div>

      <right-toolbar
        ref="rightToolBarRef"
        @queryTable="queryList"
        :searchConfig="searchConfig"
        :columns.sync="columns"
        @search="handleSearch"
      >
      </right-toolbar>
    </div>

    <div class="table_area">
      <el-table
        height="100%"
        v-loading="loading"
        :data="returnData"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
      >
        <template v-for="(item, index) in columns" :key="item.key">
          <el-table-column
            v-if="item.visible"
            :prop="item.prop"
            :label="t(`tableColumns.${item.langKey}`)"
            :width="item.width"
            :show-overflow-tooltip="true"
          >
            <template #default="{ row }">
              <div
                v-if="item.prop == 'returnNo'"
                :style="{
                  color: colors.primaryColor,
                  cursor: item.isclick ? 'pointer' : '',
                }"
                @click="openAddOrEdit(['return', 'detail'], row)"
              >
                {{ row.returnNo }}
              </div>

              <el-tag
                v-else-if="item.prop == 'enableFlag'"
                :type="
                  row.enableFlag == 0
                    ? 'danger'
                    : row.enableFlag == 1
                    ? 'warning'
                    : 'success'
                "
                >{{
                  filterStatus(row.enableFlag, "documentStatus", "id", "langKey") || "无"
                }}</el-tag
              >
              <span v-else-if="item.prop == 'createDate' || item.prop == 'returnDate'">
                {{ parseTime(row[item.prop], "{y}-{m}-{d}") || "无" }}
              </span>
              <span v-else>{{ row[item.prop] || "无" }}</span>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
    <div class="pagination-area">
      <pagination
        :total="page.total"
        v-model:page="page.pageNum"
        v-model:limit="page.pageSize"
        @pagination="queryList"
      />
    </div>
    <addOrEdit
      ref="addOrEditDialogRef"
      v-model:add-edit-info="operate"
      @getCanUseAssetsData="queryCanUseAssetsData"
      @submitAddEditInfo="submit"
      @cancelAddEditInfo="cancel"
    ></addOrEdit>
  </div>
</template>

<script setup name="returnTable">
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import colors from "@/assets/styles/variables.module.scss";
import { Edit, ArrowLeft, Document } from "@element-plus/icons-vue";
import RightToolbar from "@/components/RightToolbar";
import addOrEdit from "@/components/AshDialog/addOrEdit.vue";
import { returnColums } from "@/utils/table/columns";

import {
  GetAssetsReturnList,
  AddAssetsReturn,
  getAssetsReturnDetail,
  getAssetsCanRturn,
} from "@/api/assetsManage/receiveAndBack";
import { GetOrganizationTreeAll } from "@/api/assetsManage/organization";
import { GetUserInfoAll } from "@/api/sys/user";
import { getUserInfo } from "@/utils/auth";
import { ElMessage, ElMessageBox } from "element-plus";
const { proxy } = getCurrentInstance();
import { documentStatus } from "@/utils/statuData";
const { AssetClassification } = proxy.useDict("AssetClassification");

const returnData = ref([]); //退还列表
const loading = ref(false);
const columns = returnColums;
const page = reactive({
  total: 0,
  pageNum: 1,
  pageSize: 100,
});
const users = ref([]);
const organizes = ref([]);
const selectedOrganization = ref(null);
const dates = ref(proxy.getDefault30DaysRange());
const searchConfig = ref({
  form: {
    Dates: dates.value ? dates.value : ["", ""],
  },
  formItems: [
    {
      label: t("assetsList.assetCode"),
      prop: "assetsCode",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetCodePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetName"),
      prop: "assetsName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetNamePlaceholder"),
      },
    },
    {
      label: t("assetsList.assetType"),
      prop: "assetsClassifyId",
      type: "el-select",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.assetTypePlaceholder"),
      },
      events: {},
      options: AssetClassification,
      optionProps: {
        key: "dictionaryKey",
        label: "dictionaryName",
        value: "dictionaryCode",
      },
    },
    {
      label: t("assetsList.model"),
      prop: "specModel",
      type: "el-input",
      attrs: { clearable: true, placeholder: t("assetsList.modelPlaceholder") },
      events: {},
    },
    {
      label: t("assetsList.useUser"),
      prop: "useUserName",
      type: "el-input",
      attrs: {
        clearable: true,
        placeholder: t("assetsList.userInputPlaceholder"),
      },
      events: {},
    },
    {
      label: t("receiveAndBack.returnDate"),
      prop: "Dates",
      type: "el-date-picker",
      attrs: {
        valueFormat: "YYYY-MM-DD",
        "range-separator": t("common.to"),
        "start-placeholder": t("common.startDate"),
        "end-placeholder": t("common.endDate"),
        clearable: true,
        type: "daterange",
        "default-time": dates.value,
      },
    },
  ],
  rules: {},
});

const canUseAssetsInfo = reactive({
  data: [],
  page: {
    total: 0,
    pageNum: 1,
    pageSize: 100,
  },
  loading: false,
  searchInfo: searchConfig,
}); // 传给孙组件的资产数据
provide("canUseAssetsInfo", canUseAssetsInfo);

//组织点击获取人员
const useOrganizationNodeClick = (node) => {
  selectedOrganization.value = node;
  operate.formInfo.receiveOrganizationId = selectedOrganization.value.value;
  queryAllUsers(operate.formInfo.receiveOrganizationId);
};

const operate = reactive({
  openObj: {
    visible: false,
    openKey: "", //add edit detail
    openType: "", //维修 报废 退还 领用....
    openTitle: "",
    tableTitle: "",
    addLoading: false, //防止重复提交
  },
  formInfo: {
    returnDate: "",
    returnRemark: "",
  },
  formItems: [
    {
      label: t("receiveAndBack.returnDate"),
      prop: "returnDate",
      type: "el-date-picker",
      span: 12,
      attrs: {
        type: "date",
        "value-format": "YYYY-MM-DD",
        "disabled-date": (date) => proxy.dateAfterToday(date, true),
        clearable: true,
        disabled: true,
        placeholder: t("receiveAndBack.returnDatePlaceholder"),
      },
      events: {},
      rules: [
        {
          required: true,
          message: t("receiveAndBack.returnDateRuleErrorTip"),
          trigger: "change",
        },
      ],
    },
    {
      label: t("receiveAndBack.returnRemark"),
      prop: "returnRemark",
      type: "el-input",
      span: 24,
      attrs: {
        clearable: true,
        disabled: false,
        placeholder: t("receiveAndBack.returnRemarkPlaceholder"),
      },
      events: {},
    },
  ],

  loadingUser: false,
  tableData: [], //表格数据，添加的时候为空，其他情况为查询赋值
  toBeDelData: [], //需要移除的数据
  delList: [],
});

const rightToolBarRef = ref(null);
//1111获取列表
const queryList = () => {
  const { Dates, ...rest } = searchConfig.value.form;
  const [StartDate, EndDate] = Dates || ["", ""];
  const params = {
    pagination: page.pageNum - 1,
    pageRow: page.pageSize,
    isInit: true,
    ...rest,
    StartDate,
    EndDate,
  };
  loading.value = true;
  GetAssetsReturnList(params)
    .then((res) => {
      loading.value = false;
      returnData.value = res.output.output;
      page.total = res.output.count;
    })
    .catch((err) => {
      loading.value = false;
    });
};

//获取人员,必须先选择使用组织
const queryAllUsers = (organizeId) => {
  operate.loadingUser = true;
  GetUserInfoAll({
    subordinateDepartmentId: organizeId,
  })
    .then((res) => {
      users.value = res.output;
      operate.loadingUser = false;
    })
    .catch((err) => {
      users.value = [];
      operate.loadingUser = false;
    });
};

//查询单据详情
const queryAssetsDetail = (returnId) => {
  getAssetsReturnDetail({ returnNo: returnId }).then((res) => {
    operate.tableData = res.output;
  });
};
//222添加修改相关
const openAddOrEdit = (typeKey, row) => {
  const type = typeKey[0];
  const key = typeKey[1];
  const title =
    key == "add"
      ? t("receiveAndBack.addReturnDialogTitle")
      : key == "edit"
      ? t("receiveAndBack.editReturnDialogTitle")
      : key == "return"
      ? t("receiveAndBack.returnAssets")
      : t("receiveAndBack.viewReturnDialogTitle");
  operate.openObj = {
    visible: true,
    openKey: key,
    openType: type,
    openTitle: title,
    tableTitle: t("receiveAndBack.backAssets"),
    addLoading: false,
  };

  operate.formInfo = {
    returnDate: proxy.getNowDate(),
    ...row,
  };
  console.log(222, operate.formInfo.returnNo);
  operate.tableData = [];
  operate.toBeDelData = [];
  if (key != "add") {
    queryAssetsDetail(row.returnNo);
  }
};

//获取组织
const queryOrganization = () => {
  GetOrganizationTreeAll("")
    .then((res) => {
      organizes.value = res.output;
    })
    .catch((err) => {});
};

//添加退还单的提交
const submit = async (info) => {
  const sub = info.infoSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state ? item.state : 0,
    };
  });
  const delSub = info.delSub.map((item, index) => {
    return {
      assetsId: item.assetsId,
      assetsName: item.assetsName,
      rowId: index,
      state: item.state,
    };
  });
  if (sub.length == 0) {
    ElMessage({ message: t("common.pleaseSelectAssets"), type: "warning" });
    return;
  }
  operate.openObj.addLoading = true;
  const formAdd = {
    ...info.info,
    createUserId: JSON.parse(getUserInfo()).userId,
  };
  const formEdit = {
    ...info.info,
    updateUserId: JSON.parse(getUserInfo()).userId,
    updateUser: JSON.parse(getUserInfo()).userName,
  };
  let params = {
    Info: operate.openObj.openKey == "add" ? formAdd : formEdit,
    InfoSubList: operate.openObj.openKey == "add" ? sub : sub.concat(delSub),
  };
  const msg = operate.openObj.openKey == "add" ? t("button.add") : t("button.edit");

  try {
    const confirmed = await ElMessageBox.confirm(
      t("receiveAndBack.returnConfirmTip"),
      t("common.success"),
      {
        confirmButtonText: t("common.confirm"),
        cancelButtonText: t("common.cancel"),
        type: "warning",
      }
    );
    console.log(2);
    if (confirmed) {
      const res = await AddAssetsReturn(params);
      ElMessage({
        message: `${t("receiveAndBack.returnDocument")}:${res.output}${msg}${t(
          "common.success"
        )}`,
        type: "success",
      });

      await cancel();
      await queryList();
    }
  } catch (error) {
    operate.openObj.addLoading = false;
  }
};
//取消添加
const cancel = () => {
  operate.openObj.visible = false;
};

///3333高级搜索的
//确定高级搜索
const handleSearch = async (info) => {
  await queryList();
};

//44444444孙组件的列表数据
//获取可退还资产
const queryCanUseAssetsData = () => {
  canUseAssetsInfo.loading = true;
  let params = {
    pagination: canUseAssetsInfo.page.pageNum - 1,
    pageRow: canUseAssetsInfo.page.pageSize,
    isInit: true,
    enableFlag: 1,
    ...canUseAssetsInfo.searchInfo.form,
  };
  getAssetsCanRturn(params)
    .then((res) => {
      canUseAssetsInfo.data = res.output.output;
      canUseAssetsInfo.page.total = res.output.count;
      canUseAssetsInfo.loading = false;
    })
    .catch(() => {
      canUseAssetsInfo.data.value = [];
      canUseAssetsInfo.loading = false;
    });
};

onMounted(() => {
  queryList();
  queryOrganization();
});
</script>
<style lang="scss" scoped>
.table_container {
  padding: 0;
}
</style>
